package com.ruitaowang.goods.service;

import com.ruitaowang.account.service.SysUserService;
import com.ruitaowang.core.domain.*;
import com.ruitaowang.core.service.BaseService;
import com.ruitaowang.goods.dao.RelationsAdMapper;
import com.ruitaowang.goods.dao.RelationsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import tech.lingyi.wx.msg.out.TemplateData;
import tech.lingyi.wx.msg.out.TemplateItem;
import wx.wechat.service.mp.MPService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by neal on 11/17/16.
 */
@Service
public class RelationsService implements BaseService<Relations> {
    @Autowired
    private RelationsMapper relationsMapper;
    @Autowired
    private RelationsAdMapper relationsAdMapper;
    @Autowired
    private UserMembersService userMembersService;
    @Autowired
    private RelationsService relationsService;
    @Autowired
    private WXUserinfoService wxUserinfoService;
    @Autowired
    private SysUserService sysUserService;
    @Value("${host.api}")
    private String host;

    @Override
    public Relations insert(Relations relations) {
        if (relations.getUesrId() == null
                || relations.getPid() == null
                || relations.getUesrId().equals(relations.getPid())
                || relations.getPid() == 0){
            return null;
        }

        Relations origin = relationsMapper.selectByPK(relations.getUesrId());
        if(!ObjectUtils.isEmpty(origin) && origin.getPid() > 0){
            return null;
        }

        if(!ObjectUtils.isEmpty(origin) && origin.getPid() == relations.getPid()){
            return null;
        }

        if(!ObjectUtils.isEmpty(origin) && origin.getPid() == 0){
            origin.setPid(relations.getPid());
            Long time = System.currentTimeMillis();
            origin.setMtime(time);
//            relationsMapper.updateByPK(origin);//公众号过来的
            return null;
        }

        Long time = System.currentTimeMillis();
        relations.setCtime(time);
        relations.setMtime(time);
        relationsMapper.insert(relations);
        //sendWCM(relations.getPid());    //赠送微传媒
        //buildQRNotify(relations.getPid(),relations.getUesrId(),1);
        Relations relations1 = new Relations();
        relations1.setUesrId(relations.getPid());
        if(!ObjectUtils.isEmpty(this.select(relations1))){
            //buildQRNotify(this.select(relations1).get(0).getPid(),relations.getUesrId(),2);
        }
        return relations;
    }

    public void buildQRNotify(Long pid,Long userId,int type) {
        TemplateData templateData = TemplateData.New();
        SNSWXUserinfo snswxUserinfo = wxUserinfoService.selectByPK(pid);
        if (ObjectUtils.isEmpty(snswxUserinfo)) {
            return;
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String date =  df.format(new Date());
        templateData.setTouser(snswxUserinfo.getOpenid());
        templateData.setTemplate_id("hrYQkPtKFyVZEj5EOcCHvAyEQ0MYXGDCDQHdnDalJEQ");
        templateData.setTopcolor("FF0000");
        templateData.setData(new TemplateItem());
        if(type == 1){
            templateData.add("first", "恭喜您，您在"+ date +"成功加入了一位粉丝", "#173177");
            templateData.add("keyword2", "1级", "#0044BB");
        } else if(type == 2){
            templateData.add("first", "恭喜您，您在"+ date +"成功加入了一位粉丝", "#173177");
            templateData.add("keyword2", "2级", "#0044BB");
        }
        templateData.setUrl(host + "/wap/wx/login?fk=1-37-0-0");
        templateData.add("keyword1", sysUserService.selectByPK(userId).getNickname(), "#0044BB");
        templateData.add("keyword3", "暂无信息", "#0044BB");
        templateData.add("remark", "您可以点击详情，进入首象共享首页的个人中心进行查看", "#FF3333");
        try {
            new MPService().sendAPIEnter4TemplateMsg(templateData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 赠送微传媒
     * @param pid
     */
    private void sendWCM(long pid){
        Relations relations = new Relations();
        relations.setPid(pid);
//        long count = relationsService.count(relations);
//        if(count == 100){
//            UserMembers userMembers = new UserMembers();
//            userMembers.setUserId(pid);
//            userMembers.setRstatus((byte)0);
//            userMembers.setMemberType((byte)1);
//            List<UserMembers> userMembersList = userMembersService.select(userMembers);
//            if (!ObjectUtils.isEmpty(userMembersList)) {
//                userMembers.setMemberId(userMembersList.get(0).getMemberId());
//                userMembers.setPermanent((byte)1);
//                //赠送永久微传媒权限
//                userMembersService.update(userMembers);
//            } else {
//                UserMembers userMembers1 = new UserMembers();
//                userMembers1.setUserId(pid);
//                userMembers1.setMemberType((byte)1);
//                userMembers1.setPermanent((byte)1);
//                //赠送永久微传媒权限
//                userMembersService.insert(userMembers1);
//            }
//        } else if(count > 0 && count < 100){
//            //赠送上级一个月的微传媒
//            userMembersService.setUserMembersLimit(30,pid,(byte)1);
//        }
        //赠送上级一个月的微传媒
        userMembersService.setUserMembersLimit(30,pid,(byte)1);
    }

    @Override
    public int delete(Long id) {
        Relations relations = new Relations();
        relations.setUesrId(id);
        relations.setRstatus((byte) 1);
        Long time = System.currentTimeMillis();
        relations.setMtime(time);
        return relationsMapper.updateByPK(relations);
    }

    @Override
    public Relations update(Relations relations) {
        Long time = System.currentTimeMillis();
        relations.setMtime(time);
        relationsMapper.updateByPK(relations);
        return relations;
    }

    @Override
    public Relations selectByPK(Long id) {
        return relationsMapper.selectByPK(id);
    }

    @Override
    public List<Relations> select(Relations relations) {
        relations.setRstatus((byte) 0);
        return relationsMapper.select(relations);
    }
    public List<Relations> selectForPage(Relations relations) {
        relations.setRstatus((byte) 0);
        relations.setRecords(relationsMapper.count(relations));
        return relationsMapper.select(relations);
    }
    public long count(Relations relations) {
        relations.setRstatus((byte)0);
        return relationsMapper.count(relations);
    }

    public long spreadTwo(Long pid){
        return relationsAdMapper.spreadTwo(pid);
    }

    public List<Long> selectAllParents(Long uesrId) {
        return relationsAdMapper.selectALLParents(uesrId);
    }

    public List<Long> selectAllChild(Long userId) {
        return relationsAdMapper.selectALLChilds(userId);
    }

    public List<Relations> selectAllChildForPage(Relations relations) {
        relations.setRecords(relationsAdMapper.countALLChilds(relations));
        return relationsAdMapper.selectALLChildsForPage(relations);
    }
    //查询下两级推广人员列表
    public List<Relations> selectALLChildsTwoForPage(Relations relations) {
        relations.setRecords(relationsAdMapper.spreadTwo(relations.getPid()));
        return relationsAdMapper.selectALLChildsTwoForPage(relations);
    }
    public List<SysUser> selectALLFriends(List<Long> userIds) {
        return relationsAdMapper.selectALLFriends(userIds);
    }

    //排行榜
    public List<RelationsVO> selectPHB(RelationsVO relationsVO) {
        return relationsAdMapper.selectPHB(relationsVO);
    }
    public Long selectDZ(RelationsVO relationsVO) {
        return relationsAdMapper.selectDZ(relationsVO);
    }
    public List<SysUser> selectALLFriends(Long userId) {
        if (ObjectUtils.isEmpty(userId)){
            return null;
        }
        List<Long> list = this.selectAllChild(userId);
        if (ObjectUtils.isEmpty(list)){
            return null;
        }
        return this.selectALLFriends(list);
    }
    public List<SysUser> selectLevel1ChildForPage(Relations relations) {
        relations.setRecords(relationsMapper.count(relations));
        List<Relations> level1 = relationsMapper.select(relations);
        if (ObjectUtils.isEmpty(level1)){
            return null;
        }
        List<Long> userIds = new ArrayList<>();
        level1.forEach(item -> {
            //TODO:check is kf
            userIds.add(item.getUesrId());
        });
        List<SysUser> users = this.selectALLFriends(userIds);
        users.forEach(item -> {
            //TODO:check is kf
            if(!ObjectUtils.isEmpty(userMembersService.selectMemberForKFByUserId(item.getId()))){
                item.setUserType((byte) 6);
            }else{
                item.setUserType((byte) 0);
            }
        });
        return users;
    }

    public List<RelationsVO> selectTwoPHB(RelationsVO relationsVO) {
        return relationsAdMapper.selectTwoPHB(relationsVO);
    }
    public Long selectTowMe(RelationsVO relationsVO) {
        return relationsAdMapper.selectTowMe(relationsVO);
    }

}
